<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件档案编辑</title>
</head>
<body>
<form class="fit" id="page_doc_editor_form" enctype="multipart/form-data">
    <div class="easyui-layout" data-options="fit:true">
        <!--        <div data-options="region:'north',height:'auto'" class="form-item-style">-->
        <!--            <div style="text-align: center;width: 100%;height: 100%;margin: 0;border: 0;">-->
        <!--                <b>人事档案编辑</b>-->
        <!--            </div>-->
        <!--        </div>-->
        <div data-options="region:'center'" class="form-item-style">
            <div>
                <input name="id" type="hidden">
                <input class="easyui-combobox" name="docTypeId"
                       id="doc_docTypeId"
                       data-options="
                       labelAlign:'right',
                       url:'documentType/listQuery',
                       method:'GET',
                       queryParams:{},
                       textField:'docTypeName',
                       valueField:'id',
                       limitToList:true,
                       onLoadSuccess:function(data){

                       },
                       required:true,
                       label:'档案类型：',
                       labelWidth:100,
                       width:235">
                <input class="easyui-textbox" name="docNo"
                       data-options="
                       labelAlign:'right',
                       label:'档案登记号：',
                       labelWidth:100,
                       width:235">
                <input class="easyui-textbox" name="docName"
                       data-options="
                       labelAlign:'right',
                       label:'档案名称：',
                       required:true,
                       labelWidth:100,
                       width:235">
            </div>
            <div>
                <input class="easyui-combobox" name="docYear"
                       id="doc_docYear"
                       data-options="
                       labelAlign:'right',
                       required:true,
                       limitToList:true,
                       data:(function(){
                       let arr = [];
                       for(let i = 0;i<=45;i++){
                           arr.push({
                             text: ''+(1989 + i)
                           })
                       }
                       return arr;
                       } )(),
                       value:(function(){
                        return new Date().getFullYear();
                       })(),
                       textField:'text',
                       valueField:'text',
                       label:'档案年份：',
                       labelWidth:100,
                       width:235,required:true">
                <input class="easyui-textbox" name="saveLocation"
                       data-options="
                       labelAlign:'right',
                       label:'档案存放区域：',
                       labelWidth:100,width:235,required:false">
                <input class="easyui-combobox" name="principalId"
                       data-options="
                       url:'principal/listQuery',
                       method:'GET',
                       editable:true,
                       textField:'personName',
                       valueField:'id',
                       limitToList:true,
                       queryParams:{principalStatus:1},
                       labelAlign:'right',
                       label:'负责人：',
                       onShowPanel:function(){
                           $(this).combobox('reload');
                       },
                       labelWidth:100,
                       width:235,">
            </div>
            <div>
                <input class="easyui-combobox" name="createUserId"
                       data-options="labelAlign:'right',
                       label:'操作员：',
                       labelWidth:100,
                       url:'sysUser/listQueryByParam',
                       method:'GET',
                       width:235,
                       readonly:true,
                       textField:'userName',
                       valueField:'id',
                       panelHeight:'auto',
                       editable:false
                        ">
                <input class="easyui-datebox" name="docDate"
                       data-options="
                       labelAlign:'right',
                       label:'制作日期：',
                       value:(function(){
                       let separator = '-';
                       let date = new Date();
                       let year = date.getFullYear();
                       let month = date.getMonth() + 1;
                       let day = date.getDate();
                       return year
                              + separator
                              + (month < 10 ? ('0'+month):month)
                              + separator
                              + (day < 10 ? ('0'+day):day);
                       })(),
                       labelWidth:100,width:235">
                <input class="easyui-textbox" name="remarks"
                       data-options="labelAlign:'right',label:'备注：',labelWidth:100,width:235">
            </div>
            <div>
                <input class="easyui-textbox" name="other01"
                       data-options="labelAlign:'right',label:'其他1：',labelWidth:100,width:235">
                <input class="easyui-textbox" name="other02"
                       data-options="labelAlign:'right',label:'其他2：',labelWidth:100,width:235">
                <input class="easyui-textbox" name="other03"
                       data-options="labelAlign:'right',label:'其他3：',labelWidth:100,width:235">
            </div>
            <div>
                <input class="easyui-combotree" name="docDeptId"
                       data-options="labelAlign:'right',
                                     label:'类型：',
                                     required:true,
                                     labelWidth:100,
                                     panelHeight:250,
                                     panelWidth:180,
                                     url:'docDepartment/tree',
                                     method:'GET',
                                     queryParams:{parentId:null},
                                     textField:'text',
                                     valueField:'id',
                                     onShowPanel:function(){
                                        $(this).combotree('tree').tree('reload');
                                     },
                                     limitToList:true,
                                     onBeforeSelect:function(node){
                                        if($(this).tree('getParent',node.target)==undefined){
                                            return false;
                                        }else{
                                            return true;
                                        }
                                     },
                                     onLoadSuccess: function (node, data) {
                                            if (data != undefined && data.length > 0) {
                                                let node = $(this).tree('find', data[0].id);
                                                $(this).tree('select', node.target);
                                                //  默认折叠
                                                let children = node.children;
                                                for (let i of children) {
                                                    let item = $(this).tree('find', i.id);
                                                    if (item != undefined)
                                                        $(this).tree('collapse', item.target);
                                                }
                                            }
                                     },
                                     editable:true,
                                     width:235">
            </div>
            <div>
                <input class="easyui-textbox" data-options="
                label:'档案说明：',
                labelWidth:100,
                width:712,
                labelAlign:'right',"
                       name="documentDescribe">
            </div>
        </div>
        <div data-options="region:'south',height:310">
            <div class="tool-bar-style">
                <a class="easyui-linkbutton" data-options="plain:true"><b>附件</b></a>
                <input class="easyui-filebox" id="page_doc_editor_filebox">
                <a class="easyui-linkbutton"
                   data-options="iconCls:'icon-cancel',onClick:btn_page_doc_remove_file">删除</a>
            </div>
            <div style="height:calc(100% - 80px);width: 100%;margin: 0;border: 0;padding: 0;">
                <table id="page_doc_editor_file_grid" class="easyui-edatagrid" data-options="
                fit: true,
                rownumbers: true,
                singleSelect: true,
                fitColumns: true,
                autoSave: true,
                columns: [[
                    {title: '主键', field: 'id', hidden: true, width: 80, align: 'center', halign: 'center'},
                    {title: '外键', field: 'documentId', hidden: true, width: 80, align: 'center', halign: 'center'},
                    {title: '名称', field: 'fileName', hidden: true, width: 80, align: 'left', halign: 'center'},
                    {
                        title: '名称',
                        field: 'fileAlias',
                        width: 80,
                        align: 'center',
                        halign: 'center',
                        editor: {type: 'textbox', options: {required: true}}
                    },
                    {title: '上传日期', field: 'uploadTime', width: 80, align: 'left', halign: 'center'},
                    {title: '类型', field: 'fileType', width: 60, align: 'center', halign: 'center'},
                    {title: '操作员', field: 'createUserId', width: 55, align: 'center', halign: 'center', formatter: user_formatter},
                    {
                        title: '备注',
                        field: 'remarks',
                        width: 80,
                        align: 'center',
                        halign: 'center',
                        editor: {type: 'textbox', options: {}}
                    },
                    {title:'附件',field:'icon',width:80,align:'center',halign:'center',formatter:doc_grid_formatter},
                ]],
                onLoadSuccess:doc_grid_onLoadSuccess,
                "></table>
            </div>
            <div class="pull-right">
                <div style="height: 40px;padding: 5px;" class="linkbutton-split">
                    <a class="easyui-linkbutton"
                       data-options="iconCls:'icon-no',onClick:btn_page_doc_editor_cancel">取消</a>
                    <a class="easyui-linkbutton"
                       data-options="iconCls:'icon-save',onClick:btn_page_doc_editor_save_and_exit">保存后退出</a>
                    <a class="easyui-linkbutton"
                       data-options="iconCls:'icon-save',onClick:btn_page_doc_editor_save_and_add">保存后新增</a>
                </div>
            </div>
        </div>
    </div>
</form>
<script type="text/javascript">
    function doc_grid_formatter(v, r, i) {
        return `<a class="easyui-linkbutton" idField="${r['id']}" item="page_doc" id="${i}">预览</a>
                <a download="${r.fileName}" class="easyui-linkbutton" idField="${r['id']}" item="page_doc_download">下载</a>`
    }

    function doc_grid_onLoadSuccess() {
        $("a[item='page_doc']").linkbutton({
            iconCls: 'icon-clip',
            onClick: function () {
                let idField = $(this).attr('idField');
                if (idField != undefined) {
                    loadViewPage('docExtraFile/view/' + idField);
                }
            }
        })
        $("a[item='page_doc_download']").linkbutton({
            iconCls: 'icon-save',
            onClick: function () {
                let idField = $(this).attr('idField');
                if (idField != undefined) {
                    window.open('docExtraFile/download/' + idField, '_blank')
                }
            }
        })
    }

    //  文件
    var page_doc_editor_files = [];

    //  取消
    function btn_page_doc_editor_cancel() {
        $.messager.confirm('提示', '确定退出?编辑状态不保存!', function (r) {
            if (r) {
                $('#page_doc_editable_dialog').dialog('close');
            }
        })
    }

    //  保存并退出
    function btn_page_doc_editor_save_and_exit() {
        let title = $('#page_doc_editable_dialog').panel("header")[0].innerText;
        if (!$('#page_doc_editor_form').form('validate')) {
            $.messager.alert('提示', '请输入完整!', 'warning')
            return;
        }
        $('#page_doc_editor_file_grid').edatagrid('saveRow');
        // if (page_doc_editor_files.length > 0) {
        let formData = new FormData($('#page_doc_editor_form')[0]);
        let selected = $('#page_doc_department_tree').tree('getSelected');
        if (selected == undefined) {
            $.messager.alert('警告', '未选中文档类别!', 'error');
            return;
        }
        formData.append('docDeptId', selected.id);
        for (let i of page_doc_editor_files) {
            formData.append('files', i, i.name);
        }
        $.ajax({
            url: (function () {
                return title === '修改编辑' ? 'document/upload/update' : 'document/upload/batch'
            })(),
            type: 'POST',
            data: formData,
            beforeSend: function (xhr) {
                // $.messager.progress({title: '请等待。。。', interval: 5000});
            },
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.success) {
                    $.messager.show({title: '提示', msg: data.message});
                    let rows = $('#page_doc_editor_file_grid').datagrid('getRows');
                    if (rows.length > 0) {
                        let id = data.data.id;
                        for (let i of rows) {
                            i.documentId = id;
                        }
                        return $.ajax({
                            url: (function () {
                                return title == '修改编辑' ? 'docExtraFile/multiUpdate' : 'docExtraFile/multiInsert'
                            })(),
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(rows),
                            dataType: 'json',
                        })
                    }
                } else {
                    $.messager.show({title: '提示', msg: data.message});
                    setTimeout(function () {
                        $.messager.progress('close');
                    }, 500)
                }
            },
            error: function () {
                setTimeout(function () {
                    $.messager.progress('close');
                }, 500)
            }
        }).then(function (data) {
            if (data.success) {
                // $('#page_doc_editor_file_grid').datagrid('loadData', data.data);
                $('#page_doc_editable_dialog').dialog('close');
                page_doc_editor_files.splice(0, page_doc_editor_files.length);
                reloadDocGrid();
            }
            $.messager.show({title: data.state, msg: data.message})
            setTimeout(function () {
                $.messager.progress('close');
            }, 500)
        }, function () {
            setTimeout(function () {
                $.messager.progress('close');
            }, 500)
            $.messager.alert('提示', '发生错误,上传失败!', 'warning')
        })
        // }
    }

    //  保存并新增
    function btn_page_doc_editor_save_and_add() {
        let title = $('#page_doc_editable_dialog').panel("header")[0].innerText;
        if (!$('#page_doc_editor_form').form('validate')) {
            $.messager.alert('提示', '请输入完整!', 'warning')
            return;
        }
        $('#page_doc_editor_file_grid').edatagrid('saveRow');
        // if (page_doc_editor_files.length > 0) {
        let formData = new FormData($('#page_doc_editor_form')[0]);
        let selected = $('#page_doc_department_tree').tree('getSelected');
        if (selected == undefined) {
            $.messager.alert('警告', '未选中文档类别!', 'error');
            return;
        }
        formData.append('docDeptId', selected.id);
        for (let i of page_doc_editor_files) {
            formData.append('files', i, i.name);
        }
        // $.messager.progress({});
        $.ajax({
            url: (function () {
                return title == '修改编辑' ? 'document/upload/update' : 'document/upload/batch'
            })(),
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                if (data.success) {
                    $.messager.show({title: '提示', msg: data.message});
                    let rows = $('#page_doc_editor_file_grid').datagrid('getRows');
                    if (rows.length > 0) {
                        let id = data.data.id;
                        for (let i of rows) {
                            i.documentId = id;
                        }
                        return $.ajax({
                            url: (function () {
                                return title == '修改编辑' ? 'docExtraFile/multiUpdate' : 'docExtraFile/multiInsert'
                            })(),
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(rows),
                            dataType: 'json',
                        })
                    }
                } else {
                    $.messager.show({title: '提示', msg: data.message});
                }
            },
            error: function () {
                $.messager.progress('close');
                // $.messager.show({title: '错误', msg: "无法连接服务器"});
            }
        }).then(function (data) {
            if (data.success) {
                $('#page_doc_editor_file_grid').datagrid('loadData', {total: 0, rows: []});
                $('#page_doc_editor_form').form('clear');
                page_doc_editor_files.splice(0, page_doc_editor_files.length);
                reloadDocGrid();
                $('#page_doc_editable_dialog').dialog('close');
                btn_page_doc_add();
            }
            $.messager.show({title: data.state, msg: data.message})
        }, function () {
            $.messager.progress('close');
            $.messager.alert('提示', '发生错误,上传失败!', 'warning')
        })
        // }
    }

    //  删除文件
    function btn_page_doc_remove_file() {
        let selected = $('#page_doc_editor_file_grid').datagrid('getSelected');
        if (!selected) return;
        $('#page_doc_editor_file_grid').edatagrid('saveRow');
        $('#page_doc_editor_file_grid').datagrid('deleteRow', $('#page_doc_editor_file_grid').datagrid('getRowIndex', selected));
        for (let i = 0; i < page_doc_editor_files.length; i++) {
            if (page_doc_editor_files[i].name == selected.fileName) {
                page_doc_editor_files.splice(i, 1);
                return;
            }
        }
    }

    $(function () {
        $('#page_doc_editor_filebox').filebox({
            buttonText: '新增附件',
            buttonAlign: 'left',
            multiple: true,
            onChange: function (newVal, oldVal) {
                let files = $(this).filebox('files');
                if (files && files.length > 0)
                    for (let item of files) {
                        let row = {
                            fileName: item.name,
                            fileAlias: item.name,
                            fileType: item.type,
                            remarks: null
                        }
                        $('#page_doc_editor_file_grid').datagrid('appendRow', row);
                        page_doc_editor_files.push(item);
                    }
            }
        })
    })

    function reloadDocGrid() {
        let kGrid = $('#page_doc_grid_main').data('kendoGrid');
        if (kGrid != undefined)
            kGrid.dataSource.read({
                departmentId: (function () {
                    let selected = $('#page_doc_department_tree').tree('getSelected');
                    if (selected) {
                        if (selected.id == 1) return null;
                        return selected.id;
                    } else {
                        return null;
                    }
                })()
            });
    }

</script>
</body>
</html>